package com.geekbang.perfma4j;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 采样器
 */
public class HttpSampler implements Runnable
{
    private List<HttpSamplerListener> listeners = new ArrayList<>();
    private String url;
    private int loops;
    private final OkHttpClient okHttpClient = new OkHttpClient();

    public HttpSampler(String url, int loops)
    {
        this.url = url;
        this.loops = loops;
    }

    public void start()
    {
        Thread thread = new Thread(this);
        thread.start();
    }

    public void run()
    {
        for (int i = 0; i < loops; i++)
        {
            HttpSampleResult result = new HttpSampleResult();
            Request request = new Request.Builder().url(url).build();
            Call call = okHttpClient.newCall(request);
            long t1 = System.currentTimeMillis();
            Response response = null;
            boolean success = false;
            try
            {
                response = call.execute();
                success = response.isSuccessful();
                response.close();
            } catch (IOException e)
            {
                success = false;
            }
            long t2 = System.currentTimeMillis();
            result.setSuccess(success);
            result.setResponseTime((int) (t2 - t1));
            for (HttpSamplerListener listener : listeners)
            {
                listener.addSamplerResult(result);
            }
        }
        for (HttpSamplerListener listener : listeners)
        {
            listener.sampleEnd();
        }
    }

    void addSamplerListener(HttpSamplerListener listener)
    {
        listeners.add(listener);
    }
}
